package com.qing.picture.manager.upload;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import com.qing.picture.config.AliOssConfig;
import com.qing.picture.exception.BusinessException;
import com.qing.picture.exception.ErrorCode;
import com.qing.picture.manager.CosManager;
import com.qing.picture.model.dto.file.UploadPictureResult;

import javax.annotation.Resource;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

public abstract class PictureUploadTemplate {
    @Resource
    private AliOssConfig aliOssConfig;
    @Resource
    private CosManager cosManager;
    /**
     * 校验输入源（本地文件或 URL）
     *
     * @return
     */
    protected abstract void validPicture(Object inputSource);

    /**
     * 获取原始文件名
     * @return
     */
    protected abstract String getOriginalFilename();

    /**
     * 处理输入源并生成本地临时文件
     */
    protected abstract void processFile(Object inputSource, File file);
    /**
     * 生成上传文件名
     * @param spaceId
     * @param suffix
     * @return
     */
    private String OssUploadName(Long spaceId,String suffix) {
        String uuid = UUID.randomUUID().toString();
        String spaceName = spaceId==null?"public":spaceId.toString();
       return  new SimpleDateFormat("yyyy-MM-dd").format(new Date()) +"/"+spaceName+ "/" + uuid + "." + suffix;
    }
    /**
     * 清理临时文件
     *
     * @param file
     */
    public void deleteTempFile(File file) {
        if (file == null) {
            return;
        }
        // 删除临时文件
        boolean deleteResult = file.delete();
        if (!deleteResult) {
            System.err.println("删除临时文件失败：" + file.getAbsolutePath());
        }
    }
    /**
     * 上传图片
     *
     * @param inputSource      文件
     * @return
     */
    public UploadPictureResult uploadPicture(Object inputSource,Long spaceId) {
        // 1. 校验图片
        validPicture(inputSource);

        //获取文件名
        String fileOriginalName = getOriginalFilename();

        //获取文件名、后缀
        String fileSuffix = FileUtil.getSuffix(fileOriginalName);
        String ImgName = FileUtil.mainName(fileOriginalName);
         // 2. 上传到OSS
        String ossUploadName = OssUploadName(spaceId,fileSuffix);
        File file = null;
        try {
            // 3. 处理文件
            file = File.createTempFile(ossUploadName, null);
            processFile(inputSource,file);

            cosManager.putObject(ossUploadName, file);

            return buildResult(ImgName,ossUploadName);

        } catch (Exception e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        } finally {
           this.deleteTempFile(file);
        }
    }

    /**
     * 封装返回结果
     *
     * @return
     */
    private UploadPictureResult buildResult(String imageName, String ossUploadName) {
        String url = aliOssConfig.getHost()+"/" + ossUploadName;
        String resurl = url+"?x-oss-process=image/info";
        String   strimg =  HttpUtil.get(resurl);
        // 使用 Hutool 的 JSON 库解析响应
        JSONObject jsonObject = new JSONObject(strimg);

        String resColor = HttpUtil.get(url+"?x-oss-process=image/average-hue");
        // 解析颜色
        JSONObject colorObject = new JSONObject(resColor);


        UploadPictureResult uploadPictureResult = new UploadPictureResult();

        int picWidth = jsonObject.getByPath("ImageWidth.value", Integer.class);
        int picHeight = jsonObject.getByPath("ImageHeight.value", Integer.class);
        double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();

        uploadPictureResult.setPicName(imageName);
        uploadPictureResult.setPicWidth(picWidth);
        uploadPictureResult.setPicHeight(picHeight);
        uploadPictureResult.setPicScale(picScale);
        uploadPictureResult.setPicFormat(jsonObject.getByPath("Format.value", String.class));
        uploadPictureResult.setPicSize(Long.parseLong(jsonObject.getByPath("FileSize.value", String.class)));
        uploadPictureResult.setUrl(url+"?x-oss-process=image/format,webp");
        uploadPictureResult.setThumbnailUrl(url+"?x-oss-process=image/format,webp/resize,p_70");
        uploadPictureResult.setPicColor(colorObject.getByPath("RGB", String.class));
        return uploadPictureResult;
    }


}
